//
//  SDAlertViewController.m
//  SDAlertView
//
//  Created by sander on 2017/10/23.
//

#import "SDAlertViewController.h"

#import "SDDefineAlertContentView.h"
#import "SDActionTitleButton.h"

#import "SDAlertActionModel.h"

#import "POP.h"

#import "SDDefineActionSheetView.h"


@interface SDAlertViewController ()<UIGestureRecognizerDelegate>

@property (nonatomic, strong) UIView * customContentView;


@property (nonatomic, strong) UIView * alertContentView;

@property (nonatomic, strong) NSMutableArray<SDAlertActionModel * > * alert_action_list;

@property (nonatomic, assign) SDAlertControllerStyle alertStyle;

@end

@implementation SDAlertViewController

#pragma mark - 默认初始化 alertView title message
+ (SDAlertViewController * )alertTitle:(NSString * )title message:(NSString * )message
{
    SDAlertViewController * alert = [[SDAlertViewController alloc] init];
    alert.alertStyle = SDAlertControllerStyleAlert;
    SDDefineAlertContentView * defineAlertView = [[SDDefineAlertContentView alloc] initWithTitle:title andMessage:message];
    alert.customContentView = defineAlertView;
    
    return alert;
}

+ (SDAlertViewController * )alertTitle:(NSString * )title contentView:(UIView * )content
{
    SDAlertViewController * alert = [[SDAlertViewController alloc] init];
    alert.alertStyle = SDAlertControllerStyleAlert;
    SDDefineAlertContentView * defineAlertView = [[SDDefineAlertContentView alloc] initWithTitle:title andContentView:content];
    alert.customContentView = defineAlertView;
    return alert;
}

+ (SDAlertViewController * )actionSheetWithTitle:(NSString * )title
{
    SDAlertViewController * alert = [[SDAlertViewController alloc] init];
    alert.alertStyle = SDAlertControllerStyleActionSheet;
    SDDefineActionSheetView* actionSheet = [[SDDefineActionSheetView alloc] initWithTitle:title list:@[]];
    
    alert.customContentView = actionSheet;
    
    return alert;
}

#pragma mark - view did load
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 添加自定义的 alert的内容界面
    [self.alertContentView addSubview:self.customContentView];

    
    
    if (self.alertStyle == SDAlertControllerStyleAlert) {
        
        [self sd_configAlertButtonViewList];
        self.alertContentView.center = CGPointMake(screen_width / 2.f, screen_height / 2.f);
    }else if (self.alertStyle == SDAlertControllerStyleActionSheet){
        [self sd_configActionButtonViewList];
        self.alertContentView.frame = (CGRect){{screen_width/ 2.f - self.alertContentView.frame.size.width /2.f, screen_height}, self.alertContentView.frame.size};
    }
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                           action:@selector(touch_action:)];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
    
    // Do any additional setup after loading the view.
}

#pragma mark - view did appear
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    
    self.alertContentView.alpha = 0;
    
   
    POPBasicAnimation * animtion = [POPBasicAnimation animationWithPropertyNamed:kPOPViewAlpha];
    
    animtion.fromValue = @(0);
    animtion.toValue = @(1);
    
    [self.alertContentView pop_addAnimation:animtion forKey:@"show_alert_alpha"];
    
    if (self.alertStyle == SDAlertControllerStyleAlert) {
         self.alertContentView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.5, 0.5);
        POPSpringAnimation * springAnimtion = [POPSpringAnimation animationWithPropertyNamed:kPOPViewScaleXY];
        springAnimtion.fromValue = [NSValue valueWithCGSize:CGSizeMake(0.5, 0.5)];
        springAnimtion.toValue = [NSValue valueWithCGSize:CGSizeMake(1, 1)];
        springAnimtion.springBounciness = 12;
        [self.alertContentView pop_addAnimation:springAnimtion forKey:@"show_alert_pop"];
    }else if (self.alertStyle == SDAlertControllerStyleActionSheet) {
        POPSpringAnimation * springAnimtion = [POPSpringAnimation animationWithPropertyNamed:kPOPViewFrame];
        springAnimtion.toValue = [NSValue valueWithCGRect:(CGRect){{self.alertContentView.frame.origin.x,screen_height - self.alertContentView.frame.size.height},self.alertContentView.frame.size}];
        
        springAnimtion.springBounciness = 12;
        
        [self.alertContentView pop_addAnimation:springAnimtion forKey:@"show_actionsheet_pop"];
        
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    self.customContentView.alpha = 0;
}

#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    CGPoint point = [gestureRecognizer locationInView:self.view];
    
    if (CGRectContainsPoint(self.alertContentView.frame, point)) {
        return false;
    }
    return YES;
    
}

- (void)touch_action:(UIGestureRecognizer* )gesture
{
    __weak typeof(self) weak_self = self;
    [self dismissAlert:^{
        if (weak_self.disMissActionBlock) {
            weak_self.disMissActionBlock(weak_self);
        }
    }];
}

- (void)sd_configActionButtonViewList
{
    if ([self.customContentView isKindOfClass:[SDDefineActionSheetView class]]) {
        SDDefineActionSheetView * actionSheet = (SDDefineActionSheetView * )self.customContentView;
        actionSheet.table_height = self.action_button_height;
        
        actionSheet.list = self.alert_action_list;
    }
    self.alertContentView.frame = (CGRect){self.alertContentView.frame.origin,self.customContentView.frame.size};
}

- (void)sd_configAlertButtonViewList
{
    if (self.alert_action_list.count > 0) {
        self.alertContentView.frame = (CGRect){CGPointZero,{self.customContentView.frame.size.width,self.customContentView.frame.size.height + sizeFromPx(202)}};
    }else{
        self.alertContentView.frame = (CGRect){CGPointZero,self.customContentView.frame.size};
    }
    __block CGFloat action_origin_x = self.alertContentView.frame.size.width;
    [self.alert_action_list enumerateObjectsUsingBlock:^(SDAlertActionModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        SDActionTitleButton * button = [[SDActionTitleButton alloc] initAlertModel:obj];
        
        
        
        if (idx == 0) {
            action_origin_x = action_origin_x - sizeFromPx(30) - button.frame.size.width;
        }else if (idx == 1){
            action_origin_x = action_origin_x - sizeFromPx(150) - button.frame.size.width;
        }
        button.frame = (CGRect){{action_origin_x, CGRectGetMaxY(self.customContentView.frame) + sizeFromPx(60)}, button.frame.size};
        [self.alertContentView addSubview:button];
        
    }];
}





#pragma mark - 添加按钮
- (void)addAlertButton:(NSAttributedString *)title andActionSelected:(BOOL)isSelected alertAction:(SDActionButtonBlock)alertBlock
{
    SDAlertActionModel * model = [[SDAlertActionModel alloc] initWithTitle:title andActionBlock:alertBlock];
    model.targetController = self;
    model.isSelected = isSelected;
    [self.alert_action_list addObject:model];
}

- (void)addAlertButton:(NSAttributedString *)title alertAction:(SDActionButtonBlock)alertBlock
{
    SDAlertActionModel * model = [[SDAlertActionModel alloc] initWithTitle:title andActionBlock:alertBlock];
    model.targetController = self;
    [self.alert_action_list addObject:model];
}



//TODO: 主动 显示 alert
- (void)showAlert
{
    UIViewController * current_viewController = [SDCompositeService getCurrentViewController];
    current_viewController.definesPresentationContext = YES;
    self.view.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.3];
    self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    [current_viewController presentViewController:self animated:NO completion:nil];
}

//TODO: 主动 消失 alert
- (void)dismissAlert:(void(^)(void))completion
{
    
    if (self.alertStyle == SDAlertControllerStyleAlert) {
        POPBasicAnimation * animtion = [POPBasicAnimation animationWithPropertyNamed:kPOPViewScaleXY];
        animtion.toValue = [NSValue valueWithCGSize:CGSizeMake(0.5, 0.5)];
        animtion.duration = 0.3;
        
        __weak typeof(self)weak_self = self;
        animtion.completionBlock = ^(POPAnimation *anim, BOOL finished) {
            if (finished) {
                [weak_self dismissViewControllerAnimated:NO completion:completion];
            }
        };
        
        [self.alertContentView pop_addAnimation:animtion forKey:@"dismiss_alert_view"];
    }else if (self.alertStyle == SDAlertControllerStyleActionSheet){
        POPBasicAnimation * animtion = [POPBasicAnimation animationWithPropertyNamed:kPOPViewFrame];
        animtion.toValue = [NSValue valueWithCGRect:(CGRect){{self.alertContentView.frame.origin.x,screen_height},self.alertContentView.frame.size}];
        animtion.duration = 0.3;
        __weak typeof(self)weak_self = self;
        animtion.completionBlock = ^(POPAnimation *anim, BOOL finished) {
            if (finished) {
                [weak_self dismissViewControllerAnimated:NO completion:completion];
                
            }
        };
        
        [self.alertContentView pop_addAnimation:animtion forKey:@"dismiss_alert_view"];

    }
    

    POPBasicAnimation * alpha_animtion = [POPBasicAnimation animationWithPropertyNamed:kPOPViewAlpha];
    alpha_animtion.toValue = @(0);
    [self.alertContentView pop_addAnimation:alpha_animtion forKey:@"dismiss_alert_alpha"];
    
    
    
}

#pragma mark - lazy alert Content View
- (UIView *)alertContentView
{
    if (!_alertContentView) {
        UIView * theView = [[UIView alloc] init];
        [self.view addSubview:theView];
        theView.backgroundColor = [UIColor whiteColor];
        theView.layer.masksToBounds = true;
        theView.layer.cornerRadius = 5;
        _alertContentView = theView;
    }
    return _alertContentView;
}
#pragma mark - lazy list
- (NSMutableArray *)alert_action_list
{
    if (!_alert_action_list) {
        _alert_action_list = [[NSMutableArray alloc] init];
    }
    return _alert_action_list;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    NSLog(@"nice dealloc");
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
